<template>
  <div>
    <h1>Chat</h1>
    <div>
      <input v-model="message" @keyup.enter="sendMessage" placeholder="Type a message..." />
      <button @click="sendMessage">Send</button>
    </div>
    <div>
      <ul>
        <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

// 定义响应式状态
const message = ref('');
const messages = ref([]);
let stompClient = null;
const isConnected = ref(false); // 用于跟踪连接状态

const connect = () => {
  const socket = new SockJS('/ws');
  stompClient = Stomp.over(socket);

  stompClient.connect({}, frame => {
    console.log('Connected: ' + frame);
    isConnected.value = true; // 设置连接状态为 true

    stompClient.subscribe('/topic/messages', message => {
      messages.value.push(message.body);
    });
  }, error => {
    console.error('STOMP error: ' + error);
    isConnected.value = false; // 连接失败
  });
};

const sendMessage = () => {
  if (isConnected.value && message.value.trim()) { // 检查连接状态
    stompClient.send('/app/chat.sendMessage', {}, message.value);
    message.value = ''; // 清空输入框
  } else {
    console.error('STOMP client is not connected');
  }
};


// 使用 onMounted 生命周期钩子
onMounted(() => {
  connect();
});
</script>



<style scoped>

</style>